package com.xiaoyu.lanling.feature.generosity.dialog

import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.BaseDialogFragment
import com.xiaoyu.lanling.feature.generosity.GenerosityLevel
import com.xiaoyu.lanling.feature.generosity.GenerosityLogger
import com.xiaoyu.lanling.media.image.ImageViewUtil
import kotlinx.android.synthetic.main.generosity_level_up_dialog.*

class GenerosityLevelUpDialog : BaseDialogFragment() {
    private var showTime = 0L

    companion object {
        val TAG = GenerosityLevelUpDialog::javaClass.name
        const val KEY_LEVEL_DATA = "key_generosity_new_level"
        fun show(fragmentManager: FragmentManager, generosityLevel: GenerosityLevel) {
            val dialogFragment = fragmentManager.findFragmentByTag(TAG) as? BaseDialogFragment
                    ?: GenerosityLevelUpDialog()
            dialogFragment.arguments = Bundle().apply { putSerializable(KEY_LEVEL_DATA, generosityLevel) }
            dialogFragment.show(fragmentManager, TAG)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFullScreenDimStyle)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.generosity_level_up_dialog, container, false)
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        initView()
        initBind()
    }

    override fun onResumeSafelyAfterAppFinishInit(isFirstTimeResume: Boolean) {
        super.onResumeSafelyAfterAppFinishInit(isFirstTimeResume)
        if (isFirstTimeResume) {
            GenerosityLogger.logPushPresented()
        }
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        GenerosityLogger.logPushClosed((System.currentTimeMillis() - showTime) / 1000L)
    }

    private fun initBind() {
        close.setOnClickListener {
            dismiss()
        }
    }

    private fun initView() {
        val arg = arguments ?: return
        val generosity = arg.getSerializable(KEY_LEVEL_DATA) as? GenerosityLevel ?: return
        message.text = generosity.message
        ImageViewUtil.loadImage(avatar, generosity.avatarLoadParam)
        ImageViewUtil.loadImage(generosity_level_icon, generosity.levelIconLoadparam)
    }
}